﻿using System;
using TSites.EmailEntity.Entities;
using TSites.Utils;

namespace TSites.EmailMSMQ
{
	public class EmailMSMQ : MSMQReceiver<EmailMsgBase>
	{
		private eMailSender mailSender = null;
		public EmailMSMQ()
		{
			Initialize();
		}

		private void Initialize()
		{
			string smtpServer, smtpUid, smtpPwd, alias;
			int smtpPort;
			bool enableSSL, asynSending;

			IConfigReader appConfig = new AppConfigReader();
			smtpServer = appConfig.GetStringValue("SMTPServer");
			smtpUid = appConfig.GetStringValue("SMTPUid");
			smtpPwd = appConfig.GetStringValue("SMTPPwd");
			alias = appConfig.GetStringValue("SMTPAlias");

			smtpPort = appConfig.GetIntValue("SMTPPort");

			enableSSL = appConfig.GetBoolValue("SMTP_EnableSSL");
			asynSending = appConfig.GetBoolValue("SMTP_AsynSending");

			mailSender = new eMailSender(smtpServer, smtpPort,
				smtpUid, smtpPwd, alias,
				enableSSL, asynSending);

			// Registe event for sending email complete
			mailSender.EmailSendCompleted += new System.Net.Mail.SendCompletedEventHandler(mailSender_EmailSendCompleted);

			// MSMQ path
			msmqQueuePath = appConfig.GetStringValue("MSMQEmailPath");
		}

		private void mailSender_EmailSendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
		{
			// Insert into DB
			Console.WriteLine(DateTime.Now + ": Send mail with status = " + e.Error == null ? "OK" : e.Error.ToString());
		}

		protected override void HandleTobject(EmailMsgBase Tobject)
		{
			Tobject.BuildSubjectBody();
			mailSender.SendMail(Tobject.MailTo, Tobject.CC, Tobject.BCC,
				Tobject.Subject, Tobject.Body, Tobject.AttachedFile, true);
		}
	}
}
